#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>

using namespace std;
static const std::string default_ip = "0.0.0.0";
class server
{
public:
    server(uint16_t port, std::string ip = default_ip)
        : _ip(ip), _port(port), _sock_fd(-1)
    {
    }

    bool server_init()
    {
        // create socket
        _sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock_fd < 0)
        {
            std::cerr << "socket error:" << errno << strerror(errno) << std::endl;
            exit(0);
        }

        std::cout << "creat socket success" << std::endl;

        // bind socket
        struct sockaddr_in _addr;
        bzero(&_addr, sizeof _addr);
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        _addr.sin_port = htons(_port);

        int check = bind(_sock_fd, (sockaddr *)&_addr, sizeof _addr);
        if (check == -1)
        {
            std::cerr << "bind socket error: " << errno << strerror(errno) << std::endl;
            exit(0);
        }

        std::cout << "bind socket success" << std::endl;
    }

    bool server_start()
    {
    
        char buff[1024];
        socklen_t len = sizeof(_addr_in);
        while (true)
        {
            int size = recvfrom(_sock_fd, buff, sizeof(buff)-1 , 0,
                                    (struct sockaddr*)&_addr_in, &len);

            if (size > 0)
            {               
                buff[size] = '\0';
                std::string client_ip = inet_ntoa(_addr_in.sin_addr);
                uint16_t client_port = ntohs(_addr_in.sin_port);
                std::cout << "[" << client_ip << "]" << client_port << "#say: "<< buff << std::endl;
            }
        }
    }

    ~server()
    {}

private:
    std::string _ip;
    uint16_t _port;
    int _sock_fd;
    struct sockaddr_in _addr_in;
};

   